<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Hibernate | Cying</title><meta name="keywords" content="JavaEE"><meta name="author" content="Cying-承影"><meta name="copyright" content="Cying-承影"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Hibernate  一、入门及基本介绍1.1 - Hibernate 概述1.1.1 - 什么使框架  当我们写程序时，使用框架之后，框架帮我们实现一部分功能 使用框架的好处：少写一部分代码，实现功能   1.1.2 - 什么是 Hibernate  应用于 JavaEE 三层结构中的 DAO 层 适用于对数据库 CRUD 操作，使用 Hibernate 实现 CRUD 操作，底层代码就是 JD">
<meta property="og:type" content="article">
<meta property="og:title" content="Hibernate">
<meta property="og:url" content="http://cyingk.github.io/2020/02/15/Hibernate/index.html">
<meta property="og:site_name" content="Cying">
<meta property="og:description" content="Hibernate  一、入门及基本介绍1.1 - Hibernate 概述1.1.1 - 什么使框架  当我们写程序时，使用框架之后，框架帮我们实现一部分功能 使用框架的好处：少写一部分代码，实现功能   1.1.2 - 什么是 Hibernate  应用于 JavaEE 三层结构中的 DAO 层 适用于对数据库 CRUD 操作，使用 Hibernate 实现 CRUD 操作，底层代码就是 JD">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=607365457,3589909035&fm=26&gp=0.jpg">
<meta property="article:published_time" content="2020-02-15T15:51:01.000Z">
<meta property="article:modified_time" content="2020-07-03T16:18:16.000Z">
<meta property="article:author" content="Cying-承影">
<meta property="article:tag" content="JavaEE">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=607365457,3589909035&fm=26&gp=0.jpg"><link rel="shortcut icon" href="/img/favicon.ico"><link rel="canonical" href="http://cyingk.github.io/2020/02/15/Hibernate/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//www.clarity.ms"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>(function(c,l,a,r,i,t,y){
    c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
    t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
    y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
})(window, document, "clarity", "script", "4zndahq92q");</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true},
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: 'days',
  date_suffix: {
    just: 'Just',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"Traditional Chinese Activated Manually","cht_to_chs":"Simplified Chinese Activated Manually","day_to_night":"Dark Mode Activated Manually","night_to_day":"Light Mode Activated Manually","bgLight":"#49b1f5","bgDark":"#121212","position":"bottom-left"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: false,
  isanchor: false
};

const saveToLocal = {
  // ttl 單位是 天
  set: function setWithExpiry(key, value, ttl) {
    if (ttl === 0) return
    const now = new Date()
    const expiryDay = ttl * 86400000
    const item = {
      value: value,
      expiry: now.getTime() + expiryDay,
    }
    localStorage.setItem(key, JSON.stringify(item))
  },

  get: function getWithExpiry(key) {
    const itemStr = localStorage.getItem(key)

    if (!itemStr) {
      return undefined
    }
    const item = JSON.parse(itemStr)
    const now = new Date()

    if (now.getTime() > item.expiry) {
      localStorage.removeItem(key)
      return undefined
    }
    return item.value
  }
}

// https://stackoverflow.com/questions/16839698/jquery-getscript-alternative-in-native-javascript
const getScript = url => new Promise((resolve, reject) => {
  const script = document.createElement('script')
  script.src = url
  script.async = true
  script.onerror = reject
  script.onload = script.onreadystatechange = function() {
    const loadState = this.readyState
    if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
    script.onload = script.onreadystatechange = null
    resolve()
  }
  document.head.appendChild(script)
})</script><script id="config_change">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2020-07-04 00:18:16'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(function () {  window.activateDarkMode = function () {
    document.documentElement.setAttribute('data-theme', 'dark')
    if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
    }
  }
  window.activateLightMode = function () {
    document.documentElement.setAttribute('data-theme', 'light')
   if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
    }
  }
  const autoChangeMode = '1'
  const t = saveToLocal.get('theme')
  if (autoChangeMode === '1') {
    const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
    const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches
    const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
    const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified
    if (t === undefined) {
      if (isLightMode) activateLightMode()
      else if (isDarkMode) activateDarkMode()
      else if (isNotSpecified || hasNoSupport) {
        const now = new Date()
        const hour = now.getHours()
        const isNight = hour <= 6 || hour >= 18
        isNight ? activateDarkMode() : activateLightMode()
      }
      window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
        if (saveToLocal.get('theme') === undefined) {
          e.matches ? activateDarkMode() : activateLightMode()
        }
      })
    } else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else if (autoChangeMode === '2') {
    const now = new Date()
    const hour = now.getHours()
    const isNight = hour <= 6 || hour >= 18
    if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
    else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else {
    if (t === 'dark') activateDarkMode()
    else if (t === 'light') activateLightMode()
  }const asideStatus = saveToLocal.get('aside-status')
if (asideStatus !== undefined) {
   if (asideStatus === 'hide') {
     document.documentElement.classList.add('hide-aside')
   } else {
     document.documentElement.classList.remove('hide-aside')
   }
}const fontSizeVal = saveToLocal.get('global-font-size')
if (fontSizeVal !== undefined) {
  document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
}})()</script><meta name="generator" content="Hexo 5.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">Loading...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="/img/avatar.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">23</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">Tags</div><div class="length-num">12</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">Categories</div><div class="length-num">3</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> Home</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> Archives</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> Tags</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> Categories</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://5b0988e595225.cdn.sohucs.com/images/20190831/84729f5c5bb346208416445feb485df6.jpeg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Cying</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> Home</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> Archives</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> Tags</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> Categories</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Hibernate</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">Created</span><time class="post-meta-date-created" datetime="2020-02-15T15:51:01.000Z" title="Created 2020-02-15 23:51:01">2020-02-15</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">Updated</span><time class="post-meta-date-updated" datetime="2020-07-03T16:18:16.000Z" title="Updated 2020-07-04 00:18:16">2020-07-04</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Note/">Note</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">Word count:</span><span class="word-count">1.7k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">Reading time:</span><span>6min</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">Post View:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><html><head></head><body><h1 style="
           font-size: 60px;
           font-weight: bolder;
           border: none;
           "><center>Hibernate</center></h1>

<h1 id="一、入门及基本介绍"><a href="#一、入门及基本介绍" class="headerlink" title="一、入门及基本介绍"></a>一、入门及基本介绍</h1><h2 id="1-1-Hibernate-概述"><a href="#1-1-Hibernate-概述" class="headerlink" title="1.1 - Hibernate 概述"></a>1.1 - Hibernate 概述</h2><h3 id="1-1-1-什么使框架"><a href="#1-1-1-什么使框架" class="headerlink" title="1.1.1 - 什么使框架"></a>1.1.1 - 什么使框架</h3><blockquote>
<ul>
<li>当我们写程序时，使用框架之后，框架帮我们实现一部分功能</li>
<li>使用框架的好处：少写一部分代码，实现功能</li>
</ul>
</blockquote>
<h3 id="1-1-2-什么是-Hibernate"><a href="#1-1-2-什么是-Hibernate" class="headerlink" title="1.1.2 - 什么是 Hibernate"></a>1.1.2 - 什么是 Hibernate</h3><blockquote>
<ul>
<li>应用于 <code>JavaEE</code> 三层结构中的 <code>DAO</code> 层</li>
<li>适用于对数据库 <code>CRUD</code> 操作，使用 <code>Hibernate</code> 实现 <code>CRUD</code> 操作，底层代码就是 <code>JDBC</code> </li>
<li>开源的轻量级框架</li>
</ul>
</blockquote>
<h3 id="1-1-3-什么是-ORM"><a href="#1-1-3-什么是-ORM" class="headerlink" title="1.1.3 - 什么是 ORM"></a>1.1.3 - 什么是 ORM</h3><blockquote>
<ul>
<li><code>Object Relational Database-Mapping</code> 对象关系映射</li>
<li>让实体类和数据库进行一一对应<ul>
<li>实体类和数据表对应</li>
<li>实体类属性和表的字段</li>
</ul>
</li>
<li>不需要操作表，而是操作表对应的实体类对象</li>
</ul>
</blockquote>
<h2 id="1-2-开发环境搭建"><a href="#1-2-开发环境搭建" class="headerlink" title="1.2 - 开发环境搭建"></a>1.2 - 开发环境搭建</h2><blockquote>
<ul>
<li><p>新建一个实体类，使其对应数据库中的一条记录。这就要求实体类中的属性与表中的数据一一对应</p>
</li>
<li><p>新建一个配置文件，用于将实体类和数据表对应起来</p>
<ul>
<li><pre><code class="xml"><span class="meta"><!--?xml version="1.0" encoding="UTF-8" ?--></span>

<span class="meta">hibernate-mapping</span> <span class="meta-keyword">PUBLIC</span>
<span class="meta">        <span class="meta-string">"-//Hibernate/Hibernate Mapping DTD 3.0//EN"</span></span>
<span class="meta">        <span class="meta-string">"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"</span>></span>

<span class="tag"><<span class="name">hibernate-mapping</span>></span>

    <span class="tag"><<span class="name">class</span> <span class="attr">name</span>=<span class="string">"实体类全路径"</span> <span class="attr">table</span>=<span class="string">"数据表名"</span>></span>

        <span class="tag"><<span class="name">id</span> <span class="attr">name</span>=<span class="string">"主属性名"</span> <span class="attr">column</span>=<span class="string">"主键名"</span>></span>

            <span class="tag"><<span class="name">generator</span> <span class="attr">class</span>=<span class="string">"主键策略"</span>/></span>

        <span class="tag">< /<span class="attr">id</span>></span>

        <span class="tag"><<span class="name">property</span> <span class="attr">name</span>=<span class="string">"属性名"</span> <span class="attr">column</span>=<span class="string">"字段名"</span> <span class="attr">type</span>=<span class="string">"数据类型"</span>/></span>

    <span class="tag">< /<span class="attr">class</span>></span>

<span class="tag">< /<span class="attr">hibernate-mapping</span>></span>

- 主键策略
    - increment 自动增长
    - identity 自动增长（MySQL）
    - sequence 序列（Oricle）
    - native 根据情况自动选择
    - uuid 随机生成的一个字符串，32 位的 十六进制位
<span class="comment"><div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">Code</div></div><figure class="highlight plain"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">- 新建 `Hibernate` 的总配置文件，要求在 `src` 文件夹下，名称为 `hibernate.cfg.xml`</span><br><span class="line"></span><br><span class="line">  - ```xml</span><br><span class="line">    <!--?xml version="1.0" encoding="UTF-8" ?--></span><br><span class="line">    </span><br><span class="line">    <br><span class="line">            "-//Hibernate/Hibernate Configuration DTD 3.0//EN"</span><br><span class="line">            "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"></span><br><span class="line">    </span><br><span class="line">    <hibernate-configuration></hibernate-configuration></span><br><span class="line">    </span><br><span class="line">        <session-factory></session-factory></span><br><span class="line">    </span><br><span class="line">            <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver< /property></property></span><br><span class="line">            <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/表名< /property></property></span><br><span class="line">            <property name="hibernate.connection.username">sql用户名< /property></property></span><br><span class="line">            <property name="hibernate.connection.password">sql密码< /property></property></span><br><span class="line">    </span><br><span class="line">            # 是否显示 SQL 语句</span><br><span class="line">            <property name="hibernate.show_sql">true< /property></property></span><br><span class="line">    </span><br><span class="line">            # 是否对 SQL 语句格式规范化</span><br><span class="line">            <property name="hibernate.format_sql">true< /property></property></span><br><span class="line">    </span><br><span class="line">            # 设置表的修改方式</span><br><span class="line">            <property name="hibernate.hbm2ddl.auto">update< /property></property></span><br><span class="line">    </span><br><span class="line">            # 配置数据库的方言</span><br><span class="line">            <property name="hibernate.dialect">org.hibernate.dialect.MySQL57Dialect< /property></property></span><br><span class="line">            </span><br><span class="line">            # 配置与本地线程绑定的 Session</span><br><span class="line">            <property name="hibernate.current_session_context_class">thread< /property></property></span><br><span class="line">    </span><br><span class="line">            # 引入 实体类-数据表 配置文件</span><br><span class="line">            <mapping resource="com/cying/user.hbm.xml"></mapping></span><br><span class="line">    </span><br><span class="line">        < /session-factory></span><br><span class="line">    </span><br><span class="line">    < /hibernate-configuration></span><br></span></pre></td></tr></tbody></table></figure></div></span></code></pre>
</li>
</ul>
</li>
<li><p>开始使用</p>
<ul>
<li><pre><code class="java"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Dao</span> </span>{
    <span class="keyword">private</span> <span class="keyword">static</span> Configuration cfg = <span class="keyword">null</span>;
    <span class="keyword">private</span> <span class="keyword">static</span> SessionFactory sif = <span class="keyword">null</span>;

    <span class="keyword">static</span> {
        cfg = <span class="keyword">new</span> Configuration().configure();
        sif = cfg.buildSessionFactory();
    }

    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> SessionFactory <span class="title">getSessionFactory</span><span class="params">()</span> </span>{
        <span class="keyword">return</span> sif;
    }

}

<span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{

    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>{

        <span class="comment">// 获得会话工厂</span>
        SessionFactory sif = Dao.getSeesionFactory();

        <span class="comment">// 打开会话</span>
        Session session = sif.openSession();

        <span class="comment">// 开启事务</span>
        Transaction tx = session.beginTransaction();

        <span class="comment">// 处理逻辑;</span>

        <span class="comment">// 提交事务</span>
        tx.commit();

        <span class="comment">// 关闭会话</span>
        session.close;
        sif.close;

    }

}
<!--￼<span class="number">1</span>--></code></pre>
</li>
</ul>
</li>
</ul>
</blockquote>
<h3 id="2-2-4-delete-obj"><a href="#2-2-4-delete-obj" class="headerlink" title="2.2.4.delete(obj)"></a>2.2.4.delete(obj)</h3><blockquote>
<ul>
<li>先查询，然后使用 <code>delete()</code> 来删除</li>
</ul>
<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Object obj = session.get( Object<span class="class">.<span class="keyword">class</span>, <span class="title">id</span> )</span>;</span><br><span class="line">session.delete(obj);</span><br></pre></td></tr></tbody></table></figure></div>
</blockquote>
<h3 id="2-2-5-saveOrUpdate"><a href="#2-2-5-saveOrUpdate" class="headerlink" title="2.2.5.saveOrUpdate()"></a>2.2.5.saveOrUpdate()</h3><blockquote>
<ul>
<li>对瞬时态是 <code>save()</code></li>
<li>对持久态是 <code>update()</code></li>
<li>对托管态是 <code>update()</code></li>
</ul>
</blockquote>
<h3 id="2-2-6-Query"><a href="#2-2-6-Query" class="headerlink" title="2.2.6.Query"></a>2.2.6.Query</h3><blockquote>
<ul>
<li>不需要写 <code>sql</code> 语句，但是要写 <code>hql</code> 语句</li>
<li><code>hql (Hibernate Query Language)</code> </li>
<li><code>sql</code> 操作的是表和字段</li>
<li><code>hql</code> 操作的是实体类和属性</li>
<li><code>from 实体类名称</code> – 查询所有</li>
</ul>
</blockquote>
<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Query query = session.createQuery(<span class="string">"from User"</span>);</span><br><span class="line">List<user> list = query.list();</user></span><br></pre></td></tr></tbody></table></figure></div>

<h3 id="2-2-7-Criteria"><a href="#2-2-7-Criteria" class="headerlink" title="2.2.7.Criteria"></a>2.2.7.Criteria</h3><div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Criteria cta = session.createCreteria(obj<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">List<obj> list cta.list();</obj></span><br></pre></td></tr></tbody></table></figure></div>

<h3 id="2-2-8-SQLQuery"><a href="#2-2-8-SQLQuery" class="headerlink" title="2.2.8.SQLQuery"></a>2.2.8.SQLQuery</h3><div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 结果是数据</span></span><br><span class="line">SQLQuery sql = session.createSQLQuery(<span class="string">"SQL语句"</span>);</span><br><span class="line">List list = sql.list();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 结果是对象列表</span></span><br><span class="line">SQLQuery sql = session.createSQLQuery(<span class="string">"SQL语句"</span>);</span><br><span class="line">sql.addEntity(obj<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">List<obj> list = sql.list();</obj></span><br></pre></td></tr></tbody></table></figure></div>

<h2 id="2-3-实体类状态"><a href="#2-3-实体类状态" class="headerlink" title="2.3.实体类状态"></a>2.3.实体类状态</h2><h3 id="2-3-1-瞬时态"><a href="#2-3-1-瞬时态" class="headerlink" title="2.3.1.瞬时态"></a>2.3.1.瞬时态</h3><blockquote>
<ul>
<li>对象里没有 <code>id</code> 值，对象与 <code>session</code> 没有关联</li>
</ul>
</blockquote>
<h3 id="2-3-2-持久态"><a href="#2-3-2-持久态" class="headerlink" title="2.3.2.持久态"></a>2.3.2.持久态</h3><blockquote>
<ul>
<li>对象里面有 <code>id</code> 值，对象与 <code>session</code> 有关联</li>
</ul>
</blockquote>
<h3 id="2-3-3-托管态"><a href="#2-3-3-托管态" class="headerlink" title="2.3.3.托管态"></a>2.3.3.托管态</h3><blockquote>
<ul>
<li>对象里面有 <code>id</code> 值，对象与 <code>session</code> 没有关联</li>
</ul>
</blockquote>
<h1 id="三、Hibernate-一级缓存"><a href="#三、Hibernate-一级缓存" class="headerlink" title="三、Hibernate 一级缓存"></a>三、Hibernate 一级缓存</h1><h2 id="3-1-什么是缓存"><a href="#3-1-什么是缓存" class="headerlink" title="3.1.什么是缓存"></a>3.1.什么是缓存</h2><blockquote>
<ul>
<li>数据存到数据库里面，数据库本身是文件系统，使用流方式操作文件效率不是很高<ul>
<li>把数据存到内存里面，不需要使用流方式，可以直接读取内存中的数据</li>
<li>把数据放到内存，提供读取效率</li>
</ul>
</li>
</ul>
</blockquote>
<h2 id="3-2-Hibernate-缓存"><a href="#3-2-Hibernate-缓存" class="headerlink" title="3.2.Hibernate 缓存"></a>3.2.Hibernate 缓存</h2><blockquote>
<ul>
<li><code>Hibernate</code> 框架中提供很多优化方式，<code>Hibernate</code> 缓存就是一个优化方式</li>
</ul>
</blockquote>
<h3 id="3-2-1-一级缓存"><a href="#3-2-1-一级缓存" class="headerlink" title="3.2.1.一级缓存"></a>3.2.1.一级缓存</h3><blockquote>
<ul>
<li>默认打开</li>
<li>有使用范围（从 <code>session</code> 创建到 <code>session</code> 关闭）</li>
<li>存储数据必须是持久态</li>
<li>有一个快照区</li>
</ul>
</blockquote>
<h3 id="3-2-2-二级缓存"><a href="#3-2-2-二级缓存" class="headerlink" title="3.2.2.二级缓存"></a>3.2.2.二级缓存</h3><blockquote>
<ul>
<li>已经不用了</li>
<li>默认不打开</li>
<li>范围是整个 <code>sessionFactory</code> 范围</li>
</ul>
</blockquote>
<h1 id="四、事务的规范写法"><a href="#四、事务的规范写法" class="headerlink" title="四、事务的规范写法"></a>四、事务的规范写法</h1><div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span> {</span><br><span class="line">    <span class="comment">// 开启事务</span></span><br><span class="line">    <span class="comment">// 提交事务</span></span><br><span class="line">} <span class="keyword">catch</span>() {</span><br><span class="line">    <span class="comment">// 回滚</span></span><br><span class="line">} <span class="keyword">finally</span> {</span><br><span class="line">    <span class="comment">// 关闭</span></span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div>

<h1 id="五、绑定-Session"><a href="#五、绑定-Session" class="headerlink" title="五、绑定 Session"></a>五、绑定 Session</h1><div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">sessionFactory.getCurrentSession();</span><br><span class="line"></span><br><span class="line">- 需要配置</span><br><span class="line">    <property name="<span" class="string">"hibernate.current_session_context_class"</property></span>>thread< /property><br></pre></td></tr></tbody></table></figure></div>

<blockquote>
<p>当通过这种方式获取 <code>session</code> 时，线程结束，<code>session</code> 会自动关闭</p>
</blockquote>
<h1 id="六、多表操作"><a href="#六、多表操作" class="headerlink" title="六、多表操作"></a>六、多表操作</h1><h2 id="6-1-表与表之间关系"><a href="#6-1-表与表之间关系" class="headerlink" title="6.1.表与表之间关系"></a>6.1.表与表之间关系</h2><h3 id="6-1-1-一对多"><a href="#6-1-1-一对多" class="headerlink" title="6.1.1.一对多"></a>6.1.1.一对多</h3><blockquote>
<ul>
<li><strong>比如</strong>：分类和商品的关系，一个分类里面有多个商品，一个商品只能属于一个分类</li>
</ul>
</blockquote>
<h3 id="6-1-2-多对多"><a href="#6-1-2-多对多" class="headerlink" title="6.1.2.多对多"></a>6.1.2.多对多</h3><blockquote>
<ul>
<li><strong>比如</strong>：订单和商品关系，一个订单里有多个商品，一个商品属于多个订单</li>
</ul>
</blockquote>
<h2 id="6-2-一对多操作"><a href="#6-2-一对多操作" class="headerlink" title="6.2.一对多操作"></a>6.2.一对多操作</h2><h3 id="6-2-1-映射配置"><a href="#6-2-1-映射配置" class="headerlink" title="6.2.1.映射配置"></a>6.2.1.映射配置</h3><p><strong>创建实体类</strong></p>
<p><strong>在实体类中体现相互的关系</strong>·</p>
<p><strong>写配置文件</strong></p>
<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">xml</div></div><figure class="highlight xml"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"># 一对多中的多</span><br><span class="line"></span><br><span class="line"><span class="tag"><<span class="name">set</span> <span class="attr">name</span>=<span class="string">"属性名"</span> <span class="attr">cascade</span>=<span class="string">"save-update,delete"</span>></span></span><br><span class="line">	<span class="tag"><<span class="name">key</span> <span class="attr">column</span>=<span class="string">"外键名"</span>/></span></span><br><span class="line">    <span class="tag"><<span class="name">on-to-many</span> <span class="attr">class</span>=<span class="string">"被引用实体类全路径"</span>/></span></span><br><span class="line"><span class="tag">< /<span class="attr">set</span>></span></span><br></pre></td></tr></tbody></table></figure></div>

<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">xml</div></div><figure class="highlight xml"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"># 一对多中的一</span><br><span class="line"></span><br><span class="line"><span class="tag"><<span class="name">many-to-one</span> <span class="attr">name</span>=<span class="string">"set的属性名"</span> <span class="attr">class</span>=<span class="string">"引用实体类的全路径"</span> <span class="attr">cloumn</span>=<span class="string">"和上面的外键名一致"</span>/></span></span><br></pre></td></tr></tbody></table></figure></div>

<h3 id="6-2-2-级联保存"><a href="#6-2-2-级联保存" class="headerlink" title="6.2.2.级联保存"></a>6.2.2.级联保存</h3><blockquote>
<ul>
<li>把一加入多的 <code>Set</code> 中</li>
<li>把多加入一的属性中</li>
<li>先保存多，再保存一</li>
</ul>
<p><a href="C:%5CUsers%5CCying%5CAppData%5CRoaming%5CTypora%5Ctypora-user-images%5Cimage-20200215130137452.png" data-fancybox="group" data-caption="image-20200215130137452" class="fancybox"><img alt="image-20200215130137452" title="image-20200215130137452" data-src="C:%5CUsers%5CCying%5CAppData%5CRoaming%5CTypora%5Ctypora-user-images%5Cimage-20200215130137452.png" class="lazyload"></a></p>
</blockquote>
<h3 id="6-2-3-级联删除"><a href="#6-2-3-级联删除" class="headerlink" title="6.2.3.级联删除"></a>6.2.3.级联删除</h3><blockquote>
<ul>
<li>获取多</li>
<li>删除多</li>
</ul>
<p><a href="C:%5CUsers%5CCying%5CAppData%5CRoaming%5CTypora%5Ctypora-user-images%5Cimage-20200215170516432.png" data-fancybox="group" data-caption="image-20200215170516432" class="fancybox"><img alt="image-20200215170516432" title="image-20200215170516432" data-src="C:%5CUsers%5CCying%5CAppData%5CRoaming%5CTypora%5Ctypora-user-images%5Cimage-20200215170516432.png" class="lazyload"></a></p>
</blockquote>
<h2 id="6-3-多对多操作"><a href="#6-3-多对多操作" class="headerlink" title="6.3.多对多操作"></a>6.3.多对多操作</h2><h3 id="6-3-1-映射配置"><a href="#6-3-1-映射配置" class="headerlink" title="6.3.1.映射配置"></a>6.3.1.映射配置</h3><blockquote>
<ul>
<li>多对多需要引入第三张表</li>
</ul>
</blockquote>
<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">xml</div></div><figure class="highlight xml"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag"><<span class="name">set</span> <span class="attr">name</span>=<span class="string">"Set属性名"</span> <span class="attr">table</span>=<span class="string">"第三张表名"</span> <span class="attr">cascade</span>=<span class="string">"save-update"</span>></span></span><br><span class="line">	<span class="tag"><<span class="name">key</span> <span class="attr">column</span>=<span class="string">"在第三张表的外键名"</span>/></span></span><br><span class="line">    <span class="tag"><<span class="name">many-to-many</span> <span class="attr">class</span>=<span class="string">"另一个表对应的实体类全路径"</span> <span class="attr">column</span>=<span class="string">"另一张表在第三张表的外键名"</span>/></span></span><br><span class="line"><span class="tag">< /<span class="attr">set</span>></span></span><br></pre></td></tr></tbody></table></figure></div>

<h3 id="6-3-2-级联保存"><a href="#6-3-2-级联保存" class="headerlink" title="6.3.2.级联保存"></a>6.3.2.级联保存</h3><blockquote>
<ul>
<li>A 方加入 B 方的 Set，保存 B 方</li>
</ul>
</blockquote>
<h3 id="6-3-3-级联删除"><a href="#6-3-3-级联删除" class="headerlink" title="6.3.3.级联删除"></a>6.3.3.级联删除</h3><blockquote>
<ul>
<li>只要从数据库获取某一方，再进行删除即可，但该删除不仅会删除第三张表的对应关系，连同另一张表对应的数据也会被删</li>
</ul>
</blockquote>
<h1 id="七、查询"><a href="#七、查询" class="headerlink" title="七、查询"></a>七、查询</h1><h2 id="7-1-对象导航查询"><a href="#7-1-对象导航查询" class="headerlink" title="7.1.对象导航查询"></a>7.1.对象导航查询</h2><blockquote>
<ul>
<li>根据 <code>id</code> 查询某个客户,再查询这个客户里面所有联系人</li>
</ul>
</blockquote>
<p><strong>过程</strong></p>
<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">Code</div></div><figure class="highlight plain"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Object1 obj1 = session.get(Object1.class, id);</span><br><span class="line">Set<object2> obj2 = obj1.getobj2();</object2></span><br></pre></td></tr></tbody></table></figure></div>

<h2 id="7-2-OID-查询"><a href="#7-2-OID-查询" class="headerlink" title="7.2.OID 查询"></a>7.2.OID 查询</h2><blockquote>
<ul>
<li>根据 <code>id</code> 查询某一条记录,返回对象</li>
</ul>
</blockquote>
<p><strong>过程</strong></p>
<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Object obj = session.get(Object<span class="class">.<span class="keyword">class</span>, <span class="title">id</span>)</span>;</span><br></pre></td></tr></tbody></table></figure></div>

<h2 id="7-3-HQL-查询"><a href="#7-3-HQL-查询" class="headerlink" title="7.3.HQL 查询"></a>7.3.HQL 查询</h2><blockquote>
<ul>
<li><code>Query</code> 对象,写 <code>HQL</code> 语句实现查询</li>
<li><code>Hibernate Query Language</code> 提供一种查询语言,和普通 <code>SQL</code> 有区别</li>
</ul>
</blockquote>
<h3 id="7-3-1-查询所有"><a href="#7-3-1-查询所有" class="headerlink" title="7.3.1.查询所有"></a>7.3.1.查询所有</h3><div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Query query = session.createQuery(<span class="string">"from 实体类"</span>);</span><br><span class="line">List<object> list = query.list();<br><span class="line"></span><br><span class="line"><span class="keyword">for</span>(Object obj : list) {}</span><br></object></span></pre></td></tr></tbody></table></figure></div>

<h3 id="7-3-2-条件查询"><a href="#7-3-2-条件查询" class="headerlink" title="7.3.2.条件查询"></a>7.3.2.条件查询</h3><div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Query query = session.createQuery(from 实体类 where 实体类属性 = ? and ...);</span><br><span class="line">query.setParameter(index, value);</span><br><span class="line">List<object> list = query.list();<br><span class="line"></span><br><span class="line"><span class="keyword">for</span>(Object obj : list) {}</span><br><span class="line"></span><br><span class="line"><span class="comment">// index 从 0 开始</span></span><br></object></span></pre></td></tr></tbody></table></figure></div>

<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">Query query = session.createQuery(from 实体类 where 实体类属性 like ? and ...);</span><br><span class="line">query.setParameter(index, value);</span><br><span class="line">List<object> list = query.list();<br><span class="line"></span><br><span class="line"><span class="keyword">for</span>(Object obj : list) {}</span><br><span class="line"></span><br><span class="line"><span class="comment">// %</span></span><br><span class="line"><span class="comment">// index 从 0 开始</span></span><br></object></span></pre></td></tr></tbody></table></figure></div>

<h3 id="7-3-3-排序查询"><a href="#7-3-3-排序查询" class="headerlink" title="7.3.3.排序查询"></a>7.3.3.排序查询</h3><div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Query query = session.createQuery(from 实体类 order by 实体类属性 asc/desc);</span><br><span class="line">List<object> list = query.list();<br><span class="line"></span><br><span class="line"><span class="keyword">for</span>(Object obj : list) {}</span><br><span class="line"></span><br><span class="line"><span class="comment">// index 从 0 开始</span></span><br></object></span></pre></td></tr></tbody></table></figure></div>

<h3 id="7-3-4-分页查询"><a href="#7-3-4-分页查询" class="headerlink" title="7.3.4.分页查询"></a>7.3.4.分页查询</h3><div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">Query query = session.createQuery(from 实体类);</span><br><span class="line">query.setFirstResult(start);</span><br><span class="line">query.setMaxResult(max);</span><br><span class="line">List<object> list = query.list();<br><span class="line"></span><br><span class="line"><span class="keyword">for</span>(Object obj : list) {}</span><br><span class="line"></span><br><span class="line"><span class="comment">// index 从 0 开始</span></span><br></object></span></pre></td></tr></tbody></table></figure></div>

<h3 id="7-3-5-投影查询"><a href="#7-3-5-投影查询" class="headerlink" title="7.3.5.投影查询"></a>7.3.5.投影查询</h3><div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Query query = session.createQuery(select 属性名<span class="number">1</span>... from 实体类);</span><br><span class="line">query.setParameter(index, value);</span><br><span class="line">List<object> list = query.list();<br><span class="line"></span><br><span class="line"><span class="keyword">for</span>(Object obj : list) {}</span><br><span class="line"></span><br><span class="line"><span class="comment">// index 从 0 开始</span></span><br></object></span></pre></td></tr></tbody></table></figure></div>

<h3 id="7-3-6-聚集函数使用"><a href="#7-3-6-聚集函数使用" class="headerlink" title="7.3.6.聚集函数使用"></a>7.3.6.聚集函数使用</h3><div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Query query = session.createQuery(select 函数() from 实体类);</span><br><span class="line">Object obj = query.uniqueResult();</span><br><span class="line"></span><br><span class="line"><span class="comment">// int 需要先强转 Long,然后用 Long 的对象.intValue() 获取</span></span><br></pre></td></tr></tbody></table></figure></div></body></html></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a href="mailto:undefined">Cying-承影</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="http://cyingk.github.io/2020/02/15/Hibernate/">http://cyingk.github.io/2020/02/15/Hibernate/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/JavaEE/">JavaEE</a></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2020/02/16/SpringMVC/"><img class="prev-cover" src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=790255512,3591398303&amp;fm=26&amp;gp=0.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">Previous Post</div><div class="prev_info">SpringMVC</div></div></a></div><div class="next-post pull-right"><a href="/2020/02/14/Assembly/"><img class="next-cover" src="https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2751080876,2103309092&amp;fm=26&amp;gp=0.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">Next Post</div><div class="next_info">Assembly</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> Related Articles</span></div><div class="relatedPosts-list"><div><a href="/2020/08/06/Linux-And-Docker/" title="SpringCloud With Docker"><img class="cover" src="https://img-blog.csdnimg.cn/202008061653587.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-08-06</div><div class="title">SpringCloud With Docker</div></div></a></div><div><a href="/2020/05/05/SpringCloud/" title="SpringCloud"><img class="cover" src="http://img3.imgtn.bdimg.com/it/u=1799420697,1254911040&fm=26&gp=0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-05-05</div><div class="title">SpringCloud</div></div></a></div><div><a href="/2020/04/05/SpringBoot/" title="SpringBoot"><img class="cover" src="https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=4157804759,1050439081&fm=26&gp=0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-04-05</div><div class="title">SpringBoot</div></div></a></div><div><a href="/2020/02/20/Mybatis/" title="MyBatis"><img class="cover" src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=575314515,4268715674&fm=26&gp=0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-02-20</div><div class="title">MyBatis</div></div></a></div><div><a href="/2020/02/16/SpringMVC/" title="SpringMVC"><img class="cover" src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=790255512,3591398303&fm=26&gp=0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-02-16</div><div class="title">SpringMVC</div></div></a></div><div><a href="/2020/02/01/Struts2/" title="Struts2"><img class="cover" src="https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2597327423,2034793762&fm=26&gp=0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-02-01</div><div class="title">Struts2</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>Catalog</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link"><span class="toc-number">1.</span> <span class="toc-text">Hibernate</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%80%E3%80%81%E5%85%A5%E9%97%A8%E5%8F%8A%E5%9F%BA%E6%9C%AC%E4%BB%8B%E7%BB%8D"><span class="toc-number">2.</span> <span class="toc-text">一、入门及基本介绍</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-1-Hibernate-%E6%A6%82%E8%BF%B0"><span class="toc-number">2.1.</span> <span class="toc-text">1.1 - Hibernate 概述</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-1-%E4%BB%80%E4%B9%88%E4%BD%BF%E6%A1%86%E6%9E%B6"><span class="toc-number">2.1.1.</span> <span class="toc-text">1.1.1 - 什么使框架</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-2-%E4%BB%80%E4%B9%88%E6%98%AF-Hibernate"><span class="toc-number">2.1.2.</span> <span class="toc-text">1.1.2 - 什么是 Hibernate</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-3-%E4%BB%80%E4%B9%88%E6%98%AF-ORM"><span class="toc-number">2.1.3.</span> <span class="toc-text">1.1.3 - 什么是 ORM</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-2-%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA"><span class="toc-number">2.2.</span> <span class="toc-text">1.2 - 开发环境搭建</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-4-delete-obj"><span class="toc-number">2.2.1.</span> <span class="toc-text">2.2.4.delete(obj)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-5-saveOrUpdate"><span class="toc-number">2.2.2.</span> <span class="toc-text">2.2.5.saveOrUpdate()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-6-Query"><span class="toc-number">2.2.3.</span> <span class="toc-text">2.2.6.Query</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-7-Criteria"><span class="toc-number">2.2.4.</span> <span class="toc-text">2.2.7.Criteria</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-8-SQLQuery"><span class="toc-number">2.2.5.</span> <span class="toc-text">2.2.8.SQLQuery</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-3-%E5%AE%9E%E4%BD%93%E7%B1%BB%E7%8A%B6%E6%80%81"><span class="toc-number">2.3.</span> <span class="toc-text">2.3.实体类状态</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-1-%E7%9E%AC%E6%97%B6%E6%80%81"><span class="toc-number">2.3.1.</span> <span class="toc-text">2.3.1.瞬时态</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-2-%E6%8C%81%E4%B9%85%E6%80%81"><span class="toc-number">2.3.2.</span> <span class="toc-text">2.3.2.持久态</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-3-%E6%89%98%E7%AE%A1%E6%80%81"><span class="toc-number">2.3.3.</span> <span class="toc-text">2.3.3.托管态</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%89%E3%80%81Hibernate-%E4%B8%80%E7%BA%A7%E7%BC%93%E5%AD%98"><span class="toc-number">3.</span> <span class="toc-text">三、Hibernate 一级缓存</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#3-1-%E4%BB%80%E4%B9%88%E6%98%AF%E7%BC%93%E5%AD%98"><span class="toc-number">3.1.</span> <span class="toc-text">3.1.什么是缓存</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-2-Hibernate-%E7%BC%93%E5%AD%98"><span class="toc-number">3.2.</span> <span class="toc-text">3.2.Hibernate 缓存</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-1-%E4%B8%80%E7%BA%A7%E7%BC%93%E5%AD%98"><span class="toc-number">3.2.1.</span> <span class="toc-text">3.2.1.一级缓存</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-2-%E4%BA%8C%E7%BA%A7%E7%BC%93%E5%AD%98"><span class="toc-number">3.2.2.</span> <span class="toc-text">3.2.2.二级缓存</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%9B%9B%E3%80%81%E4%BA%8B%E5%8A%A1%E7%9A%84%E8%A7%84%E8%8C%83%E5%86%99%E6%B3%95"><span class="toc-number">4.</span> <span class="toc-text">四、事务的规范写法</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%94%E3%80%81%E7%BB%91%E5%AE%9A-Session"><span class="toc-number">5.</span> <span class="toc-text">五、绑定 Session</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%85%AD%E3%80%81%E5%A4%9A%E8%A1%A8%E6%93%8D%E4%BD%9C"><span class="toc-number">6.</span> <span class="toc-text">六、多表操作</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#6-1-%E8%A1%A8%E4%B8%8E%E8%A1%A8%E4%B9%8B%E9%97%B4%E5%85%B3%E7%B3%BB"><span class="toc-number">6.1.</span> <span class="toc-text">6.1.表与表之间关系</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#6-1-1-%E4%B8%80%E5%AF%B9%E5%A4%9A"><span class="toc-number">6.1.1.</span> <span class="toc-text">6.1.1.一对多</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-1-2-%E5%A4%9A%E5%AF%B9%E5%A4%9A"><span class="toc-number">6.1.2.</span> <span class="toc-text">6.1.2.多对多</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-2-%E4%B8%80%E5%AF%B9%E5%A4%9A%E6%93%8D%E4%BD%9C"><span class="toc-number">6.2.</span> <span class="toc-text">6.2.一对多操作</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#6-2-1-%E6%98%A0%E5%B0%84%E9%85%8D%E7%BD%AE"><span class="toc-number">6.2.1.</span> <span class="toc-text">6.2.1.映射配置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-2-2-%E7%BA%A7%E8%81%94%E4%BF%9D%E5%AD%98"><span class="toc-number">6.2.2.</span> <span class="toc-text">6.2.2.级联保存</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-2-3-%E7%BA%A7%E8%81%94%E5%88%A0%E9%99%A4"><span class="toc-number">6.2.3.</span> <span class="toc-text">6.2.3.级联删除</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-3-%E5%A4%9A%E5%AF%B9%E5%A4%9A%E6%93%8D%E4%BD%9C"><span class="toc-number">6.3.</span> <span class="toc-text">6.3.多对多操作</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#6-3-1-%E6%98%A0%E5%B0%84%E9%85%8D%E7%BD%AE"><span class="toc-number">6.3.1.</span> <span class="toc-text">6.3.1.映射配置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-3-2-%E7%BA%A7%E8%81%94%E4%BF%9D%E5%AD%98"><span class="toc-number">6.3.2.</span> <span class="toc-text">6.3.2.级联保存</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-3-3-%E7%BA%A7%E8%81%94%E5%88%A0%E9%99%A4"><span class="toc-number">6.3.3.</span> <span class="toc-text">6.3.3.级联删除</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%83%E3%80%81%E6%9F%A5%E8%AF%A2"><span class="toc-number">7.</span> <span class="toc-text">七、查询</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#7-1-%E5%AF%B9%E8%B1%A1%E5%AF%BC%E8%88%AA%E6%9F%A5%E8%AF%A2"><span class="toc-number">7.1.</span> <span class="toc-text">7.1.对象导航查询</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7-2-OID-%E6%9F%A5%E8%AF%A2"><span class="toc-number">7.2.</span> <span class="toc-text">7.2.OID 查询</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7-3-HQL-%E6%9F%A5%E8%AF%A2"><span class="toc-number">7.3.</span> <span class="toc-text">7.3.HQL 查询</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#7-3-1-%E6%9F%A5%E8%AF%A2%E6%89%80%E6%9C%89"><span class="toc-number">7.3.1.</span> <span class="toc-text">7.3.1.查询所有</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-3-2-%E6%9D%A1%E4%BB%B6%E6%9F%A5%E8%AF%A2"><span class="toc-number">7.3.2.</span> <span class="toc-text">7.3.2.条件查询</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-3-3-%E6%8E%92%E5%BA%8F%E6%9F%A5%E8%AF%A2"><span class="toc-number">7.3.3.</span> <span class="toc-text">7.3.3.排序查询</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-3-4-%E5%88%86%E9%A1%B5%E6%9F%A5%E8%AF%A2"><span class="toc-number">7.3.4.</span> <span class="toc-text">7.3.4.分页查询</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-3-5-%E6%8A%95%E5%BD%B1%E6%9F%A5%E8%AF%A2"><span class="toc-number">7.3.5.</span> <span class="toc-text">7.3.5.投影查询</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-3-6-%E8%81%9A%E9%9B%86%E5%87%BD%E6%95%B0%E4%BD%BF%E7%94%A8"><span class="toc-number">7.3.6.</span> <span class="toc-text">7.3.6.聚集函数使用</span></a></li></ol></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="footer_custom_text">却道天凉好个秋</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="Read Mode"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="Increase font size"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="Decrease font size"><i class="fas fa-minus"></i></button><button id="darkmode" type="button" title="Switch Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="Toggle between single-column and double-column"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="Setting"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="Table Of Contents"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="Back To Top"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.jsdelivr.net/npm/pangu/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script></div><canvas class="fireworks" mobile="false"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/fireworks.min.js"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>